package com.cyc.controller;

import com.alibaba.fastjson.JSON;
import com.cyc.entity.News;
import com.cyc.service.NewsService;
import com.cyc.service.impl.NewsServiceImpl;
import com.cyc.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("news")
public class NewsController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    NewsService newsService;

    @RequestMapping("all")
    @ResponseBody
    public String newsAll(){
        List<News> list =(List<News>) redisUtil.get("newsList");
        if (list==null){
            list = newsService.selectAll();
        }
        redisUtil.set("newsList",list);
        return JSON.toJSONString(list);
    }

    @RequestMapping("/select")
    public String select(Integer id, Model model){
        News news = newsService.selectByPrimaryKey(id);
        model.addAttribute("news",news);
        return "news-view";
    }

    @RequestMapping("/manAll")
    @ResponseBody
    public String manageAll(Integer page,Integer limit){
        Map<String, Object> map=new HashMap<>();
        PageHelper.startPage(page,limit);
        List<News> list = newsService.selectAll();
        PageInfo pageInfo=new PageInfo(list);
        map.put("code",0);
        map.put("msg","成功");
        map.put("count",pageInfo.getTotal());
        map.put("data",list);
        return JSON.toJSONString(map);
    }

    @ResponseBody
    @RequestMapping("del")
    public String del(Integer id){
        Map<String, Object> map=new HashMap<>();
        int i = newsService.deleteByPrimaryKey(id);
        if (i>0){
            map.put("msg","删除成功");
        }else{
            map.put("msg","删除失败");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("add")
    @ResponseBody
    public String add(News news){
        Map<String, Object> map=new HashMap<>();
        news.setCreatetime(new Date());
        int i = newsService.insert(news);
        if (i>0){
            map.put("msg","添加成功");
        }else{
            map.put("msg","添加失败");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("update")
    @ResponseBody
    public String update(News news){
        Map<String, Object> map=new HashMap<>();
        news.setCreatetime(new Date());
        int i = newsService.updateByPrimaryKey(news);
        if (i>0){
            map.put("msg","修改成功");
        }else{
            map.put("msg","修改失败");
        }
        return JSON.toJSONString(map);
    }

}
